package com.party.mobile.biz.gatherInfo;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.party.common.utils.PinyinUtil;
import com.party.common.utils.StringUtils;
import com.party.core.model.BaseModel;
import com.party.core.model.gatherInfo.GatherInfoItinerary;
import com.party.core.model.gatherInfo.GatherInfoMember;
import com.party.core.model.gatherInfo.GatherInfoProject;
import com.party.core.model.member.Member;
import com.party.core.model.member.MemberInfo;
import com.party.core.service.city.IAreaService;
import com.party.core.service.gatherInfo.IGatherInfoItineraryService;
import com.party.core.service.gatherInfo.IGatherInfoMemberService;
import com.party.core.service.gatherInfo.IGatherInfoProjectService;
import com.party.core.service.gatherInfo.biz.GatherInfoMembersBizService;
import com.party.core.service.member.IIndustryService;
import com.party.core.service.member.IMemberInfoService;
import com.party.core.service.member.IMemberService;
import com.party.mobile.biz.currentUser.CurrentUserBizService;
import com.party.mobile.biz.member.MemberBizService;
import com.party.mobile.biz.verifyCode.VerifyCodeBizService;
import com.party.core.utils.MyBeanUtils;
import com.party.mobile.web.dto.gatherInfo.output.GatherInfoMemberOutput;
import com.party.mobile.web.dto.login.output.CurrentUser;
import com.party.mobile.web.dto.login.output.MemberOutput;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class GatherInfoMemberBizService {

    @Autowired
    private GatherInfoMembersBizService gatherInfoMembersBizService;
    @Autowired
    private IGatherInfoMemberService gatherInfoMemberService;
    @Autowired
    private IGatherInfoProjectService gatherInfoProjectService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private IAreaService areaService;
    @Autowired
    private IIndustryService industryService;
    @Autowired
    private IMemberInfoService memberInfoService;
    @Autowired
    private MemberBizService memberBizService;
    @Autowired
    private VerifyCodeBizService verifyCodeBizService;
    @Autowired
    private CurrentUserBizService currentUserBizService;
    @Autowired
    private IGatherInfoItineraryService gatherInfoItineraryService;

    /**
     * 获取行程信息
     *
     * @param projectId
     * @param request
     * @return
     * @throws Exception
     */
    public Map<String, Object> getItineraryInfo(String projectId, HttpServletRequest request) throws Exception {
        Map<String, Object> map = Maps.newHashMap();
        /************************ 项目信息 ************************/
        GatherInfoProject project = gatherInfoProjectService.get(projectId);
        map.put("project", project);
        /************************ 基本信息 ************************/
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        MemberOutput memberOutput = memberBizService.getLoginMember(memberService.get(currentUser.getId()));
        map.put("member", memberOutput);
        /************************ 行程信息 ************************/
        GatherInfoMemberOutput output = new GatherInfoMemberOutput();
        GatherInfoMember memberInfoDB = gatherInfoMemberService.findByProjectAndMember(currentUser.getId(), projectId);
        if (memberInfoDB != null) {
            gatherInfoMembersBizService.formatRoomTime(memberInfoDB);
            MyBeanUtils.copyBeanNotNull2Bean(memberInfoDB, output);

            // 去程
            List<GatherInfoItinerary> goItineraries = gatherInfoItineraryService.list(new GatherInfoItinerary(memberInfoDB.getId(), "go"));
            if (goItineraries.size() == 0) {
                goItineraries.add(new GatherInfoItinerary());
            } else {
                gatherInfoMembersBizService.formatItineraryTime(goItineraries);
            }
            output.setGoItineraries(goItineraries);
            // 返程
            List<GatherInfoItinerary> backItineraries = gatherInfoItineraryService.list(new GatherInfoItinerary(memberInfoDB.getId(), "back"));
            if (backItineraries.size() == 0) {
                backItineraries.add(new GatherInfoItinerary());
            } else {
                gatherInfoMembersBizService.formatItineraryTime(backItineraries);
            }
            output.setBackItineraries(backItineraries);
        } else {
            List<GatherInfoItinerary> itineraries = Lists.newArrayList();
            itineraries.add(new GatherInfoItinerary());
            output.setGoItineraries(itineraries);
            output.setBackItineraries(itineraries);
        }
        map.put("memberInfo", output);
        return map;
    }

    /**
     * 添加人员到项目中
     *
     * @param projectId 项目id
     * @param memberId  人员id
     * @return
     */
    public GatherInfoMember addMember(String projectId, String memberId) {
        synchronized (this) {
            GatherInfoMember memberInfoDB = gatherInfoMemberService.findByProjectAndMember(memberId, projectId);
            if (memberInfoDB == null) {
                memberInfoDB = new GatherInfoMember();
                memberInfoDB.setProjectId(projectId);
                memberInfoDB.setMemberId(memberId);
                memberInfoDB.setCreateBy(memberId);
                memberInfoDB.setUpdateBy(memberId);
                memberInfoDB.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
                gatherInfoMemberService.insert(memberInfoDB);
            }

            if (memberInfoDB != null) {
                boolean flag = false;
                Member member = memberService.get(memberId);
                if (member != null && StringUtils.isEmpty(memberInfoDB.getBaseStatus())) {
                    memberInfoDB.setBaseStatus(member.getPerfectState());
                    flag = true;
                }
                MemberInfo memberInfo = memberInfoService.findByMemberId(memberId);
                if (memberInfo != null && StringUtils.isEmpty(memberInfoDB.getInsuranceStatus())) {
                    memberInfoDB.setInsuranceStatus(memberInfo.getPerfectState());
                    flag = true;
                }
                if (flag) {
                    gatherInfoMemberService.update(memberInfoDB);
                }
            }
            return memberInfoDB;
        }
    }

    /**
     * 保存用户信息
     *
     * @param currentId
     * @param t
     * @param member
     * @return
     * @throws Exception
     */
    @Transactional
    public GatherInfoMember saveItineraryInfo(String currentId, GatherInfoMember t, Member member) throws Exception {
        /************************ 基本信息 ************************/
        gatherInfoMembersBizService.updateMemberBaseInfo(member, currentId);
        /************************ 行程信息 ************************/
        // 验证当前登录用户数据
        GatherInfoMember memberInfoDB = addMember(t.getProjectId(), currentId);
        if (StringUtils.isEmpty(memberInfoDB.getItineraryStatus())) {
            memberInfoDB.setItineraryStatus("1");
        }
        gatherInfoMembersBizService.parseRoomTime(t);
        MyBeanUtils.copyBeanNotNull2Bean(t, memberInfoDB);

        memberInfoDB.setRemarks(PinyinUtil.filterEmoji(memberInfoDB.getRemarks(), ""));

        gatherInfoMemberService.update(memberInfoDB);


        gatherInfoMembersBizService.parseItineraryTime(t.getGoItineraries());
        gatherInfoMembersBizService.parseItineraryTime(t.getBackItineraries());

        List<GatherInfoItinerary> gos = gatherInfoItineraryService.list(new GatherInfoItinerary(memberInfoDB.getId(), "go"));

        gatherInfoMembersBizService.saveOrUpdate(memberInfoDB.getGoItineraries(), "go", memberInfoDB.getId(), gos);
        gatherInfoMembersBizService.saveOrUpdate(memberInfoDB.getBackItineraries(), "back", memberInfoDB.getId(), null);

        return memberInfoDB;
    }

//	/**
//	 * 填充用户
//	 *
//	 * @param memberId
//	 * @return
//	 */
//	public MemberOutput fillMember(String memberId) {
//		Member member = memberService.get(memberId);// 根据当前登录用户获取会员实体
//		MemberOutput memberOutput = MemberOutput.transform(member);
//		// 设置城市名字
//		if (!Strings.isNullOrEmpty(member.getCity())) {
//			Area area = areaService.get(member.getCity());
//			if (null != area) {
//				memberOutput.setCityId(area.getId());
//				memberOutput.setCityName(area.getName());
//			}
//		}
//		// 设置行业名字
//		if (!Strings.isNullOrEmpty(member.getIndustry())) {
//			Industry industry = industryService.get(member.getIndustry());
//			if (null != industry) {
//				memberOutput.setIndustryId(industry.getId());
//				memberOutput.setIndustry(industry.getName());
//			}
//		}
//		return memberOutput;
//	}

    /**
     * 保险保险信息
     *
     * @param currentId
     * @param memberInfo
     * @param member
     * @throws Exception
     */
    public void saveInsuranceInfo(String currentId, MemberInfo memberInfo, Member member) throws Exception {
        /************************ 基本信息 ************************/
        gatherInfoMembersBizService.updateMemberBaseInfo(member, currentId);

        /************************ 保险信息 ************************/
        String infoId = gatherInfoMembersBizService.updateMemberSatelliteInfo(memberInfo, currentId);

        MemberInfo dbInfo = memberInfoService.get(infoId);
        dbInfo.setPerfectState("1");
        memberInfoService.update(dbInfo);
    }

    /**
     * 获取保险信息
     *
     * @param request
     * @return
     */
    public Map<String, Object> getInsuranceInfo(String projectId, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        /************************ 项目信息 ************************/
        GatherInfoProject project = gatherInfoProjectService.get(projectId);
        map.put("project", project);
        /************************ 基本信息 ************************/
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        Member member = memberService.get(currentUser.getId());
        map.put("member", member);
        /************************ 保险信息 ************************/
        MemberInfo memberInfo = memberInfoService.findByMemberId(currentUser.getId());
        if (memberInfo == null) {
            memberInfo = new MemberInfo();
        }
        GatherInfoMember infoMember = gatherInfoMemberService.findByProjectAndMember(currentUser.getId(), projectId);
        map.put("status", infoMember != null ? infoMember.getInsuranceStatus() : "");
        map.put("memberInfo", memberInfo);
        return map;
    }

    /**
     * 获取基本信息
     *
     * @param projectId
     * @param request
     * @return
     */
    public Map<String, Object> getBaseInfo(String projectId, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        /************************ 项目信息 ************************/
        GatherInfoProject project = gatherInfoProjectService.get(projectId);
        map.put("project", project);
        /************************ 基本信息 ************************/
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        MemberOutput memberOutput = memberBizService.getLoginMember(memberService.get(currentUser.getId()));
        map.put("member", memberOutput);
//        Member member = memberService.get(currentUser.getId());
//        map.put("member", member);
        GatherInfoMember infoMember = gatherInfoMemberService.findByProjectAndMember(currentUser.getId(), projectId);
        map.put("status", infoMember != null ? infoMember.getBaseStatus() : "");
        MemberInfo memberInfo = memberInfoService.findByMemberId(memberOutput.getRegistrationId());
        if (memberInfo == null) {
            memberInfo = new MemberInfo();
        }
        map.put("memberInfo", memberInfo);
        return map;
    }

    /**
     * 保存基本信息
     *
     * @param currentId
     * @param member
     * @param request
     */
    public void saveBaseInfo(String currentId, Member member, MemberInfo memberInfo, HttpServletRequest request) {
        /************************ 基本信息 ************************/
        gatherInfoMembersBizService.updateMemberBaseInfo(member, currentId);

        Member dbMember = memberService.get(currentId);
        dbMember.setCountryCode(member.getCountryCode());
        dbMember.setPerfectState("1");
        memberService.update(dbMember);

        gatherInfoMembersBizService.updateMemberInfoHealth(memberInfo, currentId);
    }

//	/**
//	 * 绑定手机
//	 *
//	 * @param member
//	 * @param verifyCode
//	 * @param request
//	 * @param memberOutput
//	 * @return
//	 */
//	public CurrentUser bindPhone(Member member, String verifyCode, HttpServletRequest request, MemberOutput memberOutput) {
//		// 获取登陆用户
//		CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
//		// 如果当前登录用户是第三方授权用户，且手机号为空，则需要绑定手机号
//		if (CurrentUser.isThirdparty(currentUser)) {
//			// 验证码验证
//			boolean verifyResult = verifyCodeBizService.verify(member.getMobile(), verifyCode);
//			if (verifyResult) {
//				// 绑定手机号
//				memberOutput = memberBizService.bindPhone(member.getMobile(), member.getRealname(), member.getCompany(), member.getJobTitle(),
//						member.getIndustry(), request);
//				// 当前登录用户需重新赋值
//				currentUser = currentUserBizService.getCurrentUserByToken(memberOutput.getToken());
//			}
//		}
//		return currentUser;
//	}
}
